package com.ha.auto_skip;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.ha.auto_skip.adapter.AppInfoAdapter;
import com.ha.auto_skip.bean.AppInfoBean;
import com.ha.auto_skip.databinding.ActivityAppListBinding;
import com.ha.auto_skip.utils.SpacesItemDecoration;
import com.xinkao.skmvp.utils.CustomProgressDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AppListActivity extends AppCompatActivity {

    ActivityAppListBinding binding;

    AppInfoAdapter adapter;

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    CustomProgressDialog mCPDialog;

    /**
     * 搜索关键词
     */
    String mSearchKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityAppListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("应用列表");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        mCPDialog = new CustomProgressDialog(this);
        mCPDialog.show();
        executorService.execute(() -> {
            List<AppInfoBean> list = getAppList();

            runOnUiThread(() -> {
                adapter.reloadData(list);
                mCPDialog.dismiss();
            });
        });

        adapter = new AppInfoAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.addItemDecoration(new SpacesItemDecoration(0, 18, 4, 18));
        binding.recyclerView.setAdapter(adapter);

        initSetListener();

    }

    private void initSetListener() {
        adapter.setOnItemClickListener((view, viewType, data, position) -> {
            // 返回选择的软件包信息
//            MMKVUtils.getInstance().saveString(App.START_APP_KEY, data.getPackage_name());
            Intent intent = new Intent();
            intent.putExtra("appName", data.getLabel());
            intent.putExtra("appPackage", data.getPackage_name());
            setResult(0xBC, intent);
            finish();
        });

        binding.search.setOnClickListener(view ->  {
            mCPDialog.show();

            mSearchKey = binding.searchKey.getText().toString();
            executorService.execute(() -> {
                List<AppInfoBean> list = getAppList();

                runOnUiThread(() -> {
                    adapter.reloadData(list);
                    mCPDialog.dismiss();
                });
            });
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private List<AppInfoBean> getAppList() {
        ArrayList<AppInfoBean> appBeanList = new ArrayList<>();
        AppInfoBean bean = null;

        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (PackageInfo p : list) {
            bean = new AppInfoBean();
            bean.setIcon(p.applicationInfo.loadIcon(packageManager));
            bean.setLabel(packageManager.getApplicationLabel(p.applicationInfo).toString());
            bean.setPackage_name(p.applicationInfo.packageName);
            int flags = p.applicationInfo.flags;
            // 判断是否是属于系统的apk
            if (TextUtils.isEmpty(mSearchKey)) {
                if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                } else {
                    if (!getPackageName().equals(bean.getPackage_name())) {
                        appBeanList.add(bean);
                    }
                }
            } else {
                if (!getPackageName().equals(bean.getPackage_name())) {
                    if (bean.getLabel().contains(mSearchKey)) {
                        appBeanList.add(bean);
                    }
                }
            }

//            if (!getPackageName().equals(bean.getPackage_name())) {
//                appBeanList.add(bean);
//            }
        }
        return appBeanList;
    }
}